package com.yihuier.yihuier.Service.MeetingManager;

import com.yihuier.yihuier.Controller.UserManager.UserController;
import com.yihuier.yihuier.Entity.MeetingManager.*;
import com.yihuier.yihuier.Entity.MeetingManager.DTO.MeetingApplyDTO;
import com.yihuier.yihuier.Entity.MeetingManager.DTO.MeetingApplyInfoDTO;
import com.yihuier.yihuier.Entity.MeetingManager.DTO.MeetingDTO;
import com.yihuier.yihuier.Entity.RoomManager.Room;
import com.yihuier.yihuier.Mapper.MeetingManager.*;
import com.yihuier.yihuier.Mapper.RoomManager.RoomMapper;
import com.yihuier.yihuier.Mapper.UserManager.DepartmentMapper;
import com.yihuier.yihuier.Mapper.UserManager.DepartmentUserMapper;
import com.yihuier.yihuier.Mapper.UserManager.UserMapper;
import com.yihuier.yihuier.Util.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.yihuier.yihuier.Mapper.Config.SelectConfig.DEFAULT_OFFSET;
import static com.yihuier.yihuier.Mapper.Config.SelectConfig.DEFAULT_ROWS;

@Service
public class MeetingService {

    @Autowired
    private MeetingMapper meetingMapper;

    @Autowired
    private MeetingRoomMapper meetingRoomMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private MeetingUserMapper meetingUserMapper;

    @Autowired
    private MeetingAttendMapper meetingAttendMapper;

    @Autowired
    private MeetingApplyMapper meetingApplyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DepartmentUserMapper departmentUserMapper;

    @Autowired
    private UserController userController;

    /**
     * 获取最新的会议
     * @param offset 偏移量
     * @param rows 用户量
     * @return 用户的结果集
     */
    public List<Meeting> getLatestMeetings(int offset, int rows){
        if (offset == -1){
            //如果不设置偏移量则默认0
            offset = DEFAULT_OFFSET;
        }
        if (rows == -1){
            //如果不设置结果量则默认10
            rows = DEFAULT_ROWS;
        }
        return meetingMapper.selectLatestMeeting(offset,rows);
    }

    /**
     * 获取用户即将参加的两次会议的信息
     * */
    public ArrayList<Map<String,Object>> getLatestTwoMeetingInfomation(int user_id){
        return meetingMapper.selectLatestTwoMeetingInfomation(user_id);
    }

    /**
     * 获取用户即将参加所有会议的信息
     * */
    public ArrayList<Map<String,Object>> getAllMeetingInfomation(int user_id){
        return meetingMapper.selectAllMeetingInfomation(user_id);
    }

    public List<Map<String,Object>> getCollectionMeetings(int[] meeting_ids){
        return meetingMapper.selectCollectionMeetingsByMeetingIdArray(meeting_ids);
    }

    /**
     * 根据单个meeting_id获取我收藏的会议一部分信息
     * */
    public Map<String,Object> getCollectionMeetingInfoByMeetingId(Long meeting_id){
        return meetingMapper.selectCollectionMeetingInfoByMeetingId(meeting_id);
    }

    /**
     * 根据单个meeting_id获取会议一部分信息
     * */
    public Map<String,Object> getMeetingInfoByMeetingId(int meeting_id){
        return meetingMapper.selectMeetingInfoByMeetingId(meeting_id);
    }


    public int getNumOfReadyMeetingByUser(int [] meets){
        if (meets.length == 0){
            return 0;
        }
        return meetingMapper.selectNumOfReadyMeetingByUser(meets);
    }
    public int getNumOfClosedMeetingByUser(int [] meets){
        if (meets.length == 0){
            return 0;
        }
        return meetingMapper.selectNumOfClosedMeetingByUser(meets);
    }
    public int getNumOfInvalidMeetingByUser(int [] meets){
        if (meets.length == 0){
            return 0;
        }
        return meetingMapper.selectNumOfInvalidMeetingByUser(meets);
    }

    public int addOneBasicMeetingApply(
            String meetingName
            , Timestamp meeting_time
            ,int during_time
            ,int location
            ,int em_number
            ,String em_list
            ,int status
            ,int user_id
            ,String hardware
            ,int isIntellgence
            ,String other
            ,String description){
        this.meetingApplyMapper.addOneBasicMeetingApply(meetingName,meeting_time,during_time,em_number,em_list,status,user_id,hardware,isIntellgence,other,description);
        int meeting_apply_id = this.meetingApplyMapper.selectOneLastMeetingApplyId();
        if (location != 0){
            this.meetingApplyMapper.updateMeetingApplyLocation(meeting_apply_id,location);
        }
        return meeting_apply_id;
    }

    public int addOneBasicMeeting(
            String meetingName
            ,int em_number
            ,int meeting_status
            ,int user_id
            ,String description){
        if (this.meetingMapper.addOneBasicMeeting(meetingName,em_number,meeting_status,user_id,description) > 0){
            return this.meetingMapper.selectOneLastMeetingId();
        }else {
            return 0;
        }
    }

    /**
     * 得到我参加的会议信息
     * */
    public ArrayList<Map<String,Object>> getRelatedToMeMeetingInfomation(int user_id){
        return this.meetingMapper.selectRelatedToMeMeetingInfomation(user_id);
    }

    /**
     * 预定一个会议室
     * @return 会议室信息
     * @param userId 用户ID
     * @param required_room_id 要求会议室ID
     * @param meeting_time 开会时间
     * @param lastTime 持续时间
     * @param hardware 硬件要求
     * @param people 人员列表
     * @param other 备注
     * @param meetingName 会议名称
     */
    public Room bookOneMeeting(int userId
            , int required_room_id
            , Timestamp meeting_time
            , int lastTime
            , List<String> hardware
            , List<Integer> people
            , String other
            , String meetingName
            , int meeting_apply_id
            , String description){
        Room room = null;
        boolean usable = false;
        long startTime = 0;
        long endTime = 0;
        int room_id = 0;
        if (required_room_id == 0){
            //会议室没定
            if (meeting_time == null){
                //时间没定
                return null;
            }else {
                //时间定好了
                usable = false;
                List<Room> rooms = this.roomMapper.selectAvailbleRooms(this.departmentMapper.selectCompanyIdByDepartmentId(this.departmentUserMapper.selectDepartmentIdByUserid(userId))
                        ,meeting_time
                        ,new Timestamp(meeting_time.getTime() + 60000 * lastTime));
                if (rooms == null || rooms.isEmpty()){
                    return null;
                }
                for (Room tempRoom : rooms){
                    if (seeRoomFit(tempRoom,hardware,people.size())){
                        //匹配成功
                        usable = true;
                        room = tempRoom;
                        startTime = meeting_time.getTime();
                        endTime = startTime + lastTime * 60000;
                        break;
                    }
                }
                if (!usable){
                    return null;
                }
            }
        }else {
            //会议室定好了
            room = checkRoomIsAvailble(required_room_id);
            if (room == null){
                //该会议室不能用
                return null;
            }
            if (meeting_time == null){
                //时间没定
                Calendar today = new GregorianCalendar();
                Calendar moring = new GregorianCalendar();
                Calendar afternoon = new GregorianCalendar();
                {
                    today.setTime(new Date());
                    today.set(Calendar.HOUR_OF_DAY,8);
                    today.set(Calendar.MINUTE,0);
                    today.set(Calendar.SECOND,0);

                    moring.setTime(new Date());
                    moring.set(Calendar.HOUR_OF_DAY,8);
                    moring.set(Calendar.MINUTE,0);
                    moring.set(Calendar.SECOND,0);

                    afternoon.setTime(new Date());
                    afternoon.set(Calendar.HOUR_OF_DAY,17);
                    afternoon.set(Calendar.MINUTE,0);
                    afternoon.set(Calendar.SECOND,0);
                }
                usable = false;
                startTime = 0;
                endTime = 0;
                for (int i = 0 ; i < 5 ; i++){
                    today.add(Calendar.DATE,1);
                    moring.add(Calendar.DATE,1);
                    afternoon.add(Calendar.DATE,1);
                    List<MeetingRoom> meetingRoomList = this.meetingRoomMapper.selectMeetingRoomToday(required_room_id,new Timestamp(today.getTime().getTime()));

                    long lastTimeMills = 60000 * lastTime;

                    if (meetingRoomList.isEmpty()){
                        startTime = moring.getTime().getTime();
                        endTime = startTime + lastTimeMills;
                    }else {
                        MeetingRoom temp = meetingRoomList.get(meetingRoomList.size() - 1);
                        System.out.println(temp);
                        if (temp.getMeeting_time_end().getTime() >= afternoon.getTime().getTime()){
                            continue;
                        }else {
                            usable = true;
                            startTime = temp.getMeeting_time_end().getTime() + 20 * 60000;
                            endTime = startTime + lastTimeMills;
                            break;
                        }
                    }
                }
            }else {
                //时间定好了
                List<MeetingRoom> meetingRoomList = this.meetingRoomMapper.selectMeetingRoomInfoBetweenNowAndThenByRoomId(required_room_id,meeting_time);
                usable = true;
                startTime = meeting_time.getTime();
                endTime = startTime + lastTime * 60000;
                for (MeetingRoom meetingRoom : meetingRoomList){
                    if (
                            (
                                    meetingRoom.getMeeting_time_end().getTime() > startTime
                                    &&
                                    meetingRoom.getMeeting_time_end().getTime() < endTime
                            )
                            ||
                            (
                                    meetingRoom.getMeeting_time_start().getTime() > startTime
                                    &&
                                    meetingRoom.getMeeting_time_start().getTime() < endTime
                            )
                    ){
                        usable = false;
                        break;
                    }
                }
            }
        }
        if (usable){
            this.meetingMapper.addOneBasicMeeting(meetingName,people.size(),0,userId,description);
            int meeting_id = this.meetingMapper.selectOneLastMeetingId();
            for (int tempUserId : people) {
                this.meetingUserMapper.addOneRecordOfMeetingUserWithOutRole(tempUserId,meeting_id);
                this.meetingAttendMapper.addOneRecordOfMeetingUserWithOutReason(tempUserId,meeting_id);
            }
            this.meetingMapper.updateMeetingLocation(meeting_id,room.getRoom_id());
            this.meetingApplyMapper.updateMeetingApplyStatus(meeting_apply_id,1);
            this.meetingRoomMapper.insetOneMeeting(room.getRoom_id(),meeting_id,new Date(startTime),lastTime,new Date(endTime));
            final long transStartTime = startTime;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 通知用户
                    int [] tempPeople = people.stream().mapToInt(Integer::valueOf).toArray();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println(sdf.format(new Date(transStartTime)));
                    userController.sendMessage(userId,tempPeople,meetingName,sdf.format(transStartTime), String.valueOf(lastTime));
                    // 生成二维码
                    QRCodeUtil.zxingCodeCreate("0," + meeting_id,"0" + meeting_id,250);
                }
            }).start();
        }else {
            this.meetingApplyMapper.updateMeetingApplyStatus(meeting_apply_id,0);
        }
        return usable ? room : null;
    }

    public Room checkRoomIsAvailble(int room_id){
        if(this.roomMapper.selectRoomParentStatus(room_id) != 1){
            //会议室暂时无法使用
            return null;
        }
        return this.roomMapper.selectRoomById(room_id);
    }

    public boolean seeRoomFit(Room room, List<String> gears, int emNum){
        if (emNum > room.getRoom_capacity()){
            return false;
        }

        boolean [] check = new boolean[gears.size()];
        if (room.getRoom_hardware() == null || room.getRoom_hardware().equals("")){
            return false;
        }
        String[] roomHave = room.getRoom_hardware().split(",");

        for (int i = 0 ; i < check.length ; i++){
            check[i] = false;
            for (int  j = 0 ; j < roomHave.length ; j ++){
                if (roomHave[j].equals(gears.get(i))){
                    check[i] = true;
                    break;
                }
            }
        }
        for (int i = 0 ; i < check.length ; i++){
            if (!check[i]){
                return false;
            }
        }
        return true;
    }

    /**
     * 根据用户输入内容模糊查询与我有关的会议
     * */
    public ArrayList<Map<String,Object>> getRelatedToMeMeetingIdAndMeetingNameByVague(String content, int user_id){
        return meetingMapper.selectRelatedToMeMeetingIdAndMeetingNameByVague(content,user_id);
    }

    /**
     * 根据会议编号获得会议所在location
     * */
    public int getLocationByMeetingId(int meeting_id){
        return meetingMapper.selectLocationByMeetingId(meeting_id);
    }

    public List<MeetingDTO> getReadyMeetingByUser(int [] meets){

        return meetingMapper.selectMeetingByUserAndStatus(meets,0);
    }
    public List<MeetingDTO> getClosedMeetingByUser(int [] meets){

        return meetingMapper.selectMeetingByUserAndStatus(meets,3);
    }
    public List<MeetingDTO> getInvalidMeetingByUser(int [] meets){

        return meetingMapper.selectMeetingByUserAndStatus(meets,4);
    }

    public List<MeetingApplyInfoDTO> getMeetingApplyByStatus(int status, int user_id){
        List<MeetingApply> meetingApplies =  this.meetingApplyMapper.selectMeetingApplyByStatus(status,user_id);
        List<MeetingApplyInfoDTO> meetingApplyInfoDTOS = new LinkedList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (MeetingApply meetingApply : meetingApplies){
            MeetingApplyInfoDTO meetingApplyInfoDTO = new MeetingApplyInfoDTO();

            meetingApplyInfoDTO.setApp_meeting_id(meetingApply.getApp_meeting_id());
            meetingApplyInfoDTO.setApp_name(meetingApply.getApp_name());
            meetingApplyInfoDTO.setApp_description(meetingApply.getApp_description());
            if (meetingApply.getMeeting_time() == null){
                meetingApplyInfoDTO.setMeeting_time("");
            }else {
                meetingApplyInfoDTO.setMeeting_time(sdf.format(meetingApply.getMeeting_time()));
            }

            meetingApplyInfoDTO.setDuring_time(meetingApply.getDuring_time());
            meetingApplyInfoDTO.setLocation(meetingApply.getLocation());
            meetingApplyInfoDTO.setEm_number(meetingApply.getEm_number());
            meetingApplyInfoDTO.setEm_list(getPeopleListFromStr(meetingApply.getEm_list()));
            meetingApplyInfoDTO.setStatus(meetingApply.getStatus());
            meetingApplyInfoDTO.setApplicant(meetingApply.getApplicant());
            meetingApplyInfoDTO.setHardware(meetingApply.getHardware_applicant());
            meetingApplyInfoDTO.setIsIntelligence_allocation(meetingApply.getIsIntelligence_allocation());
            meetingApplyInfoDTO.setOther(meetingApply.getOther());

            String locationName;

            if (meetingApply.getLocation() == null){
                locationName = "";
            }else {
                locationName   = roomMapper.selectRoomNameByRoomId(meetingApply.getLocation());
                if (locationName == null || locationName.equals("")){
                    continue;
                }
            }
            
            meetingApplyInfoDTO.setLocationName(locationName);

            meetingApplyInfoDTOS.add(meetingApplyInfoDTO);
        }
        if (meetingApplyInfoDTOS.isEmpty()){
            return null;
        }else {
            return meetingApplyInfoDTOS;
        }
    }
    public boolean auditMeetingApply(MeetingApplyDTO meetingApplydDTO, int user_id) {
        if (this.roomMapper.selectRoomParentStatus(meetingApplydDTO.getLocation())!= 1){
            // 该会议室暂时不可用
            return false;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = null;
        try {
            startTime = sdf.parse(meetingApplydDTO.getMeeting_time());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date endTime = new Date(startTime.getTime() + meetingApplydDTO.getDuring_time()*60000);

        if (this.meetingRoomMapper.selectThisTimeRoomIfUsing(meetingApplydDTO.getLocation(),startTime,endTime)>0) {
            // 该会议室被占用了，不可用
            return false;
        }
        int [] peopleList = getPeopleListFromStr(meetingApplydDTO.getEm_list());
        switch (meetingApplydDTO.getStatus()){
            case 0:
                // 未通过
                this.meetingApplyMapper.updateMeetingApplyStatus(meetingApplydDTO.getApp_meeting_id(),0);
                break;
            case 1:
                // 审核通过
                this.meetingMapper.addOneBasicMeeting(meetingApplydDTO.getApp_name(),peopleList.length,0,meetingApplydDTO.getApplicant(),meetingApplydDTO.getApp_description());
                int meeting_id = this.meetingMapper.selectOneLastMeetingId();
                for (int tempUserId : peopleList) {
                    this.meetingUserMapper.addOneRecordOfMeetingUserWithOutRole(tempUserId,meeting_id);
                    this.meetingAttendMapper.addOneRecordOfMeetingUserWithOutReason(tempUserId,meeting_id);
                }
                this.meetingMapper.updateMeetingLocation(meeting_id,meetingApplydDTO.getLocation());
                this.meetingApplyMapper.updateMeetingApplyStatus(meetingApplydDTO.getApp_meeting_id(),1);
                this.meetingRoomMapper.insetOneMeeting(meetingApplydDTO.getLocation(),meeting_id,startTime,meetingApplydDTO.getDuring_time(),endTime);
                break;
            case 2:
                // 正在审核
                this.meetingApplyMapper.updateMeetingApplyStatus(meetingApplydDTO.getApp_meeting_id(),2);
                break;
            case 3:
                // 还未审核
                this.meetingApplyMapper.updateMeetingApplyStatus(meetingApplydDTO.getApp_meeting_id(),3);
                break;
        }
        return true;
    }

    private int[] getPeopleListFromStr(String em_list) {

        String [] temp = em_list.split(",");

        int [] result = new int[temp.length];
        for (int i = 0 ; i < result.length ; i++){
            result[i] = Integer.parseInt(temp[i]);
        }
        return result;
    }

    /**
     * 根据时间改变会议状态
     * */
    public int updateMeetingStatus(int meeting_id,int meeting_status){
        return meetingMapper.updateMeetingStatus(meeting_id,meeting_status);
    }

    public boolean tryToAddOneUserIntoMeeting(int meeting_id,int user_id){

        if (this.meetingUserMapper.addOneRecordOfMeetingUserWithRole(user_id,meeting_id,2) <= 0){
            return false;
        }

        return true;
    }

    public String getMeetingNameById(int meeting_id){
        return meetingMapper.selectMeetingNameById(meeting_id);
    }

}
